package com.eryos.android.cigarettecounter.database;

/**
 * Project :  CigaretteCounter
 * Author :   Olivier Combe 
 * URL :      http://eryos.fr/CigaretteCounter/
 *
 * Copyright (C) 2011 - Olivier Combe 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter 
{ 
    private static final String TAG 				= "DBAdapter";
    
    private static final String DATABASE_NAME 		= "eryos.db";
    private static final int 	DATABASE_VERSION 	= 8;
    
    protected static final String DATABASE_TABLE 	= "smoke_table";
    protected static final String KEY_ROWID 		= "_id";
    protected static final String KEY_SMOKE_TIME 	= "smoke_time";
    protected static final String KEY_SMOKE_REASON 	= "smoke_reason";
    protected static final String KEY_SMOKE_PRICE  	= "smoke_valid";

    private static final String DATABASE_CREATE =
        "CREATE TABLE "+DATABASE_TABLE+" ( "
	        + KEY_ROWID 	   + " INTEGER PRIMARY KEY AUTOINCREMENT, "
	        + KEY_SMOKE_TIME   + " DATETIME DEFAULT CURRENT_TIMESTAMP, "
	        + KEY_SMOKE_REASON + " TEXT,"
	        + KEY_SMOKE_PRICE  + " TEXT"
        + ");";
        
    protected final Context context;      
	protected DatabaseHelper DBHelper;
    protected SQLiteDatabase db;

    /**
     * 
     * @param ctx
     */
    public DBAdapter(Context ctx) {
        this.context = ctx;
        
        open();
    }
    
    /**
     * 
     * @return
     * @throws SQLException
     */
    public DBAdapter open() throws SQLException {    	
        if ( db == null || ! db.isOpen() ){
        	Log.w(getClass().getSimpleName(), "Open DB connection");
        	DBHelper = new DatabaseHelper(context);
        	db = DBHelper.getWritableDatabase();
        }
        return this;
    }

    /**
     * 
     */
    public void close() {    	
    	if ( db.isOpen() ){
    		Log.w(getClass().getSimpleName(), "Close DB connection");
    		db.close();
    		DBHelper.close();    
    	}
    }
    
    /**
     * 
     * @param _reason
     * @param price
     */
    public void insertCurrentTimestamp(String _reason, float price){
    	Log.i(getClass().getSimpleName(), "Insert Current TS");
    	long epoch = System.currentTimeMillis()/1000;
    	if ( price < 0 )
    		price = 0;
    	db.execSQL("INSERT INTO "+DATABASE_TABLE+" VALUES ( null, datetime("+epoch+", 'unixepoch', 'localtime'), '"+_reason+"', '"+price+"');");        
    }
    
    /**
     * 
     * @param _reason
     * @param price
     */
    public void insertCurrentTime(String _reason, float price) {
    	Log.i(getClass().getSimpleName(), "Insert Current Time");
    	if ( price < 0 )
    		price = 0;
    	db.execSQL("INSERT INTO "+DATABASE_TABLE+" VALUES ( null, datetime(), '"+_reason+"', '"+price+"');");        
    }
    
    /**
     * 
     */
    public void deleteAll() {  
    	Log.i(getClass().getSimpleName(), "Delete All Data");
    	System.out.println("DELETE ALL DATA ....");
    	db.execSQL("DELETE FROM "+DATABASE_TABLE+";");        
    }

    /** ************************************************************************** **/    
    
    /**
     * 
     */
    private static class DatabaseHelper extends SQLiteOpenHelper 
    {
        /**
         * 
         * @param context
         */
    	DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

    	@Override
    	public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion 
                  + " to "
                  + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
            onCreate(db);
        }
    }
}